/**
 *
 */
package com.bys.ots.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bys.ots.controller.ComplaintController;
import com.bys.ots.dao.ComplaintRecordMapper;
import com.bys.ots.model.Complaint;
import com.bys.ots.model.ComplaintRecord;
import com.bys.ots.model.Email;
import com.bys.ots.pojo.ConstantModel;
import com.bys.ots.pojo.ResultEnum;
import com.bys.ots.service.MailService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bys.ots.dao.ComplaintMapper;
import com.bys.ots.pojo.Result;
import com.bys.ots.pojo.ResultUtil;
import com.bys.ots.service.ComplaintService;
import org.springframework.util.ObjectUtils;

import java.io.*;
import java.net.URLDecoder;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author bairuihua
 * 2019/12/03
 */
@Service("complaintService")
public class ComplaintServiceImpl implements ComplaintService {

    private final Logger logger = LoggerFactory.getLogger(ComplaintServiceImpl.class);

    @Autowired
    private ComplaintMapper complaintMapper;
    @Autowired
    private ComplaintRecordMapper complaintRecordMapper;
    @Autowired
    private MailService mailService;
    @Autowired
    ConstantModel constantModel;

    @Override
    public Result getAllComplaint() {
        return ResultUtil.OTSResult(complaintMapper.findAll());
    }

    @Override
    public Result insertComplaint(Complaint complaint) {
        String uuid = UUID.randomUUID().toString();
        complaint.setDescriptionId(uuid);
        complaint.setIsDeleted(0);
        int i = complaintMapper.insert(complaint);
        if (i == 0) {
            return ResultUtil.error(ResultEnum.CODE_426);
        }
        return ResultUtil.success();
    }

    @Override
    public Result sendComplaintEmail(String raw) {
        JSONObject jsonObj = JSONObject.parseObject(raw);
        String so = jsonObj.getString("so");
        String userId = jsonObj.getString("userId");
        String description = jsonObj.getString("description");
        String type = jsonObj.getString("catalog");
        if (StringUtils.isEmpty(so)) {
            return ResultUtil.error(ResultEnum.CODE_406);
        }
        if (StringUtils.isEmpty(userId)) {
            return ResultUtil.error(ResultEnum.CODE_410);
        }
        ComplaintRecord complaintRecord = complaintRecordMapper.findByUserIdAndSoAndNow(userId, so);
        if (!ObjectUtils.isEmpty(complaintRecord)) {
            return ResultUtil.error(ResultEnum.CODE_433);
        }
        ComplaintRecord complaintRecord2 = new ComplaintRecord();
        complaintRecord2.setUserId(userId);
        complaintRecord2.setSo(so);
        complaintRecordMapper.insert(complaintRecord2);
        List<Email> emails = complaintRecordMapper.findEmailBySo(so);
        if (ObjectUtils.isEmpty(complaintRecord) && !ObjectUtils.isEmpty(emails)) {
            for (Email email : emails) {
                if (StringUtils.isNotEmpty(email.getEmail())) {
                    mailService.sendComplaintEmail(email.getEmail(), "[TFS Transparency - " + type + "] SO:" + so, so, userId, type, description);
                }
            }
            return ResultUtil.success();
        } else {
            return ResultUtil.OTSResult(ResultEnum.CODE_432);
        }

    }

    public void sendEmail(JSONObject jsonObject) {
        Boolean bool = false;
        String json = "";
        for (String tmp : jsonObject.keySet()) {
            json += tmp + "=" + jsonObject.getString(tmp).replace("???","不存在") + "&";
        }
        json = json.substring(0, json.length() - 1);
        for (String entry : json.split("&")) {
            String date = entry.split("=")[1];
            if (org.apache.commons.lang3.StringUtils.equals("不存在", date)) {
                bool = true;
                break;
            }
            if (org.apache.commons.lang3.StringUtils.equals("Sale Rep Mapping.xlsx", entry.split("=")[0])) {
                continue;
            }
            DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime datefile = LocalDateTime.parse(date.substring(0, date.length() - 4), dtf2);
            LocalDateTime now = LocalDateTime.now();
            Duration duration = Duration.between(datefile, now);
            long hours = duration.toHours();
            if (hours > 15) {
                bool = true;
                break;
            }
        }
        sendFileGeneEmail(json, bool);
    }

    public void sendFileGeneEmail(String json, Boolean bool) {
//        if (!bool) {
//            return;
//        }
        String body = "文件名称" + " " + "生成时间" + "</br>";
        for (String entry : json.split("&")) {
            if (StringUtils.equals("不存在", entry.split("=")[1])) {
                body += "<span style=\"color:#dc3545\">" + entry.split("=")[0] + "    " + entry.split("=")[1] + "</span></br>";
                continue;
            }

            String fileDate = entry.split("=")[1].substring(0, entry.split("=")[1].length() - 4);
            if (StringUtils.equals("Sale Rep Mapping.xlsx", entry.split("=")[0])) {
                body += entry.split("=")[0] + "    " + fileDate + "</br>";
                continue;
            }
            DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime datefile = LocalDateTime.parse(fileDate, dtf2);
            LocalDateTime now = LocalDateTime.now();
            Duration duration = Duration.between(datefile, now);
            long hours = duration.toHours();
            if (hours > 15) {
                body += "<span style=\"color:#dc3545\">" + entry.split("=")[0] + "    " + fileDate + "</span></br>";
            } else {
                body += entry.split("=")[0] + "    " + fileDate + "</br>";
            }

        }
        mailService.sendEmail(constantModel.getFileExceptionHeader(), body + constantModel.getFileExceptionBody(), "bairui.hua@163.com", "DMZ 同步文件巡检通知prod", "");
      //  mailService.sendEmail(constantModel.getFileExceptionHeader(), body + constantModel.getFileExceptionBody(), "mark.zhu@thermofisher.com", "DMZ 同步文件巡检通知", "");
      //  mailService.sendEmail(constantModel.getFileExceptionHeader(), body + constantModel.getFileExceptionBody(), "byron.shi@thermofisher.com", "DMZ 同步文件巡检通知", "");
      //  mailService.sendEmail(constantModel.getFileExceptionHeader(), body + constantModel.getFileExceptionBody(), "lianjun@beyondsoft.com", "DMZ 同步文件巡检通知", "");
    }

    private String getTwoLevel(Object num) {
        String tar = "" + num;
        if (tar.length() == 1) {
            tar = "0" + tar;
        }
        return tar;
    }

    public void checkProduce() {
        File file = new File("/home/ubuntu/DataImportFailed");
        LocalDateTime nowDate = LocalDateTime.now();
        String body = "";
        File[] files = file.listFiles();
        for (File fielTem : files) {
            String tar = "" + nowDate.getYear() + getTwoLevel(nowDate.getMonthValue()) + getTwoLevel(nowDate.getDayOfMonth());
            if ((fielTem.getName().indexOf(tar) != -1)) {
                int i = fielTem.getName().indexOf(".txt");
                body += fielTem.getName().substring(0, i + 4) + "<br/>";

            }
        }
//        if (StringUtils.isEmpty(body)) {
//            return;
//        }
        mailService.sendEmail(constantModel.getFileAnalysisExceptionHeader(), body + constantModel.getFileAnalysisExceptionBody(), "bairui.hua@163.com", "赛默飞文件解析异常", "");
        mailService.sendEmail(constantModel.getFileAnalysisExceptionHeader(), body + constantModel.getFileAnalysisExceptionBody(), "mark.zhu@thermofisher.com", "赛默飞文件解析异常", "");
        mailService.sendEmail(constantModel.getFileAnalysisExceptionHeader(), body + constantModel.getFileAnalysisExceptionBody(), "byron.shi@thermofisher.com", "赛默飞文件解析异常", "");
        mailService.sendEmail(constantModel.getFileAnalysisExceptionHeader(), body + constantModel.getFileAnalysisExceptionBody(), "lianjun@beyondsoft.com", "赛默飞文件解析异常", "");
    }

    public void checkRecord(JSONObject jsonObject) {
        logger.info("开始生成RecordDate.txt");
        String json = "";
        for (String tmp : jsonObject.keySet()) {
            json += tmp + "=" + jsonObject.getString(tmp).replace("???","不存在") + "&";
        }

        json = json.substring(0, json.length() - 1);
        File file = new File("/home/ubuntu/SapTextData/" + "RecordDate.txt");
        try {
            if (!file.exists()) {
                File.createTempFile("RecordDate", ".txt", new File("/home/ubuntu/SapTextData/"));
            }
            BufferedWriter writer = new BufferedWriter(new FileWriter(file, false));
            writer.write("fileName" + " " + "lastModifyDate" + "\r\n");
            for (String entry : json.split("&")) {
                writer.write(entry.split("=")[0] + "    " + entry.split("=")[1] + "\r\n");
            }
            writer.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
